<template>
  <div>
    <!-- 搜索和按钮 -->
    <el-form inline>
      <el-form-item>
        <el-input placeholder="用户名" v-model="searchObj.username" />
      </el-form-item>
      <el-button type="primary" @click="search" icon="el-icon-search">查询</el-button>
      <el-button type="default" @click="clearInput">清空</el-button>
    </el-form>
    <!-- 添 加和批量删除 -->
    <div style="margin-bottom: 20px">
      <el-button type="primary" @click="showAddUser">添 加</el-button>
      <el-button type="danger">批量删除</el-button>
    </div>
    <!-- 用户列表 -->
    <el-table border stripe v-loading="listLoading" :data="userlist.items">
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" label="序号" width="80" align="center" />
      <el-table-column prop="username" label="用户名" width="150" />
      <el-table-column prop="nickName" label="用户昵称" />
      <el-table-column prop="roleName" label="角色列表" />
      <el-table-column prop="gmtCreate" label="创建时间" width="180" />
      <el-table-column prop="gmtModified" label="更新时间" width="180" />
      <el-table-column label="操作" width="230" align="center">
        <template slot-scope="{ row }">
          <el-button
            type="info"
            icon="el-icon-user-solid"
            size="small"
            @click="showRole(row)"
            title="分配角色"
            v-if="$hasBP('btn.User.assgin')"
          />
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="small"
            @click="showUpdateUser(row)"
            title="修改角色"
            v-if="$hasBP('btn.User.update')"
          />
          <el-popconfirm
            :title="`确定删除  ${row.username} 吗?`"
            @confirm="removeUser(row.id)"
          >
            <template #reference>
              <el-button
                style="margin-left: 10px"
                type="danger"
                size="small"
                icon="el-icon-delete"
                title="删除用户"
                v-if="$hasBP('btn.User.remove')"
              />
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      :current-page="page"
      :total="userlist.total"
      :page-size="limit"
      :page-sizes="[3, 6, 9]"
      style="padding: 20px 0"
      layout="prev, pager, next, jumper, ->, sizes, total"
      @current-change="getUserlist"
      @size-change="handleSizeChange"
    />
    <!-- 点击添加按钮的dialog -->
    <el-dialog
      :title="userObj.id ? '修改用户' : '添加用户'"
      :visible.sync="dialogUserVisible"
    >
      <el-form
        :model="userObj"
        ref="userForm"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userObj.username" />
        </el-form-item>
        <el-form-item label="用户昵称">
          <el-input v-model="userObj.nickName" />
        </el-form-item>
        <el-form-item v-if="!userObj.id" label="用户密码" prop="password">
          <el-input v-model="userObj.password" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="addOrUpdate('userForm')"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <!-- 分配角色 -->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogTableVisible1"
      top="0"
      :data="userlist.items"
    >
      <el-form label-width="150px">
        <el-form-item label="用户名" prop="username" :rules="rules">
          <el-input
            v-model="name"
            autocomplete="off"
            size="small"
            :disabled="true"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色列表">
          <el-checkbox
            :indeterminate="isIndeterminate"
            v-model="checkAll"
            @change="handleCheckAllChange"
            >全选</el-checkbox
          >
          <div style="margin: 5px 0"></div>
          <el-checkbox-group
            v-model="checkedRole"
            @change="handleCheckedCitiesChange"
          >
            <el-checkbox
              v-for="role in allRole"
              :label="role.id"
              :key="role.id"
              >{{ role.roleName }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="roleSave" size="mini">保存</el-button>
        <el-button @click="dialogTableVisible1 = false" size="mini"
          >取消</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "user",
  data() {
    return {
      userlist: [], // 当前页的用户列表
      user: {}, // 当前要操作的user
      listLoading: false, // 是否显示列表加载的提示
      page: 1, // 当前页码
      limit: 3, // 每页数量
      total: 0, // 总数量
      userObj: {
        username: "",
        nickName: "",
        password: "",
      },
      //控制dialog的展示与隐藏
      dialogUserVisible: false,
      //控制分配角色的dialog
      dialogTableVisible1: false,
      //收集搜索条件输入的对象
      searchObj: {
        username: "",
      },
      selectedIds: [], // 所有选择的user的id的数组
      //表单验证
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "change" },
          { min: 3, message: "用户名最少4个字符", trigger: "change" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "change" },
          { min: 6, message: "密码不可少于6位", trigger: "change" },
        ],
      },

      //角色列表的数据
      allRole: [],
      checkedRole: [],
      isIndeterminate: true,
      checkAll: false,
      name: "",
    };
  },

  mounted() {
    this.getUserlist();
  },

  methods: {
    // 获取用户列表
    async getUserlist(page = 1) {
      //切换页码
      this.page = page;
      // this.limit = limit
      //调用接口发送请求
      let result = await this.$API.UserApi.getUserList(
        page,
        this.limit,
        this.searchObj
      );
      this.userlist = result.data;
    },

    //pageSize 发生改变的回调
    handleSizeChange(pageSize) {
      this.limit = pageSize;
      this.getUserlist();
    },

    //点击添加按钮
    showAddUser() {
      this.user = {};
      this.dialogUserVisible = true;
      this.userObj = {
        username: "",
        nickName: "",
        password: "",
      };
      //清空表单验证
      this.$nextTick(() => this.$refs.userForm.clearValidate());
    },
    //点击取消按钮隐藏dialog
    cancel() {
      this.dialogUserVisible = false;
      this.user = {};
    },
    //点击dialog确定按钮
    async addOrUpdate(userForm) {
      this.$refs[userForm].validate(async (valid) => {
        if (valid) {
          let result = await this.$API.UserApi.addOrUpdateUser(this.userObj);
          //关闭对话框
          this.dialogUserVisible = false;
          // 重新发送请求
          this.getUserlist();
        } else {
          return false;
        }
      });
    },
    //点击修改角色
    showUpdateUser(row) {
      this.dialogUserVisible = true;
      this.userObj = row;
    },
    //点击删除按钮
    async removeUser(id) {
      let result = await this.$API.UserApi.removeById(id);
      this.$message.success("删除成功");
      this.getUserlist(this.userlist.length === 1 ? this.page - 1 : this.page);
    },
    //分配角色
    async showRole(row) {
      // 存储ID以便复选框保存按钮使用
      this.userObj.id = row.id;
      this.name = row.username;
      this.dialogTableVisible1 = true;
      let result = await this.$API.UserApi.getRoles(row.id);
      //全部角色列表
      this.allRole = result.data.allRolesList;
      // 已分配的角色列表
      this.checkedRole = result.data.assignRoles.map((item) => item.id);
      this.isIndeterminate =
        result.data.assignRoles.length > 0 &&
        result.data.assignRoles.length < result.data.allRolesList.length;
      this.checkAll =
        result.data.allRolesList.length === result.data.assignRoles.length;
      this.userlist.id = row.id;
    },
    //点击全选复选框
    handleCheckAllChange(val) {
      this.isIndeterminate = false;
      this.checkedRole = val ? this.allRole.map((item) => item.id) : [];
    },
    // 点击单个复选框的回调
    handleCheckedCitiesChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.allRole.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.allRole.length;
      this.checkedRole = value;
    },
    //点击分配角色dialog保存按钮
    async roleSave() {
      let userId = this.userlist.id;
      let roleId = this.checkedRole.join(',');
      let result = await this.$API.UserApi.reqDoAssign(userId,roleId);
      this.dialogTableVisible1 = false;
      //重新获取用户列表
      this.getUserlist()
    },
    //点击搜索框
    search(){
      this.searchObj = this.userObj;
      this.getUserlist();
    },
    //点击清空按钮
    clearInput(){
      this.searchObj = "";
      this.getUserlist();
    }
  },
};
</script>

<style scoped></style>
